package com.edu.compile.template.model;

import com.edu.compile.util.ParamUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author yanzhao
 * @date 2021/10/31 22:50
 * @since 1.0.0
 */
@Data
public class UrlPath implements Serializable {

    private Boolean hasHeadSeparator;
    private Boolean hasTailSeparator;
    private List<SubPath> subPaths;

    public UrlPath merge() {
        Optional<List<SubPath>> optional = Optional.ofNullable(this.subPaths);
        if (optional.isPresent()) {
            List<SubPath> mergePaths = new ArrayList<>();

            SubPath mergePath = null;
            StringBuilder buffer = new StringBuilder();
            for (SubPath subPath : subPaths) {
                if (subPath.getIsParam()) {
                    Optional.ofNullable(mergePath).ifPresent((path) -> mergePaths.add(path));
                    mergePaths.add(subPath);
                    mergePath = null;
                } else {
                    mergePath = Optional.ofNullable(mergePath).orElse(new SubPath());
                    mergePath.setIsParam(false);

                    if (StringUtils.isNotBlank(mergePath.getPath())) {
                        buffer.append(mergePath.getPath()).append(ParamUtils.URL_SEPARATOR).append(subPath.getPath());
                    } else {
                        buffer.append(subPath.getPath());
                    }
                    mergePath.setPath(buffer.toString());
                    buffer.setLength(0);
                }
            }
            this.subPaths = mergePaths;
        }
        return this;
    }

    @Override
    public String toString() {
        return "UrlPath{" +
                "subPaths=" + subPaths +
                '}';
    }
}
